//
//  UIViewController+Dev.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/19.
//

import UIKit

public extension UIViewController {

    static var currentVC: UIViewController? {
        return getTopVC(withRootVC: UIApplication.shared.keyWindow?.rootViewController)
    }
    static var currentNav: UINavigationController? {
        return currentVC?.navigationController
    }
}

public extension UIApplication {
    
    static var keyWindowNow: UIWindow? {
        
        return UIApplication.shared.keyWindow
//        var window = UIApplication.keyWindow
//        if #available(iOS 13.0, *) {
//            window = UIApplication.shared.windows.filter({$0.isKeyWindow}).last
//        }
//        return window
    }
    
    static var currentVC: UIViewController? {
        guard
            let tabbarVC = keyWindowNow?.rootViewController as? UITabBarController
            else { return nil }
        return getTopVC(withRootVC: tabbarVC)
    }
    
    static var currentNav: UINavigationController? {
        return currentVC?.navigationController
    }
}

private func getTopVC(withRootVC rootVC: UIViewController?) -> UIViewController? {
    guard let root = rootVC else { return nil }
    if root is UITabBarController {
        return getTopVC(withRootVC: (root as? UITabBarController)?.selectedViewController)
    }
    else if root is UINavigationController {
        return getTopVC(withRootVC: (root as? UINavigationController)?.visibleViewController)
    }
    else if let modalVC = root.presentedViewController {
        return getTopVC(withRootVC: modalVC)
    }
    else {
        return root
    }
}

